package com.example.dockercompose.dao;

import com.example.dockercompose.mapper.StationMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import java.io.InputStream;
import java.io.StringReader;

public class TestDao {
    private static final Logger logger = LoggerFactory.getLogger(TestDao.class);

    private static SqlSessionFactory sqlSessionFactory;

    public static void buildSqlSessionFactory() {
        try {
            logger.info("load mybatis.xml");
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            InputStream inputStream = resourceLoader.getResource("classpath:mybatis.xml").getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            StringReader stringReader = new StringReader(new String(bytes));
            logger.info("mybatis config {}", new String(bytes));

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(stringReader, "development");
            sqlSessionFactory.getConfiguration().getMapperRegistry().addMapper(StationMapper.class);
//            sqlSessionFactory.getConfiguration().getMapperRegistry().addMappers("com.example.dockercompose.mapper");
            logger.info("start mybatis ok.");
        } catch (Exception e) {
            logger.error("start mybatis error", e);
        }
    }

    public String test() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            logger.info("mysql {}", session.getMapper(StationMapper.class).findAll().size());
        }
        return "test";
    }


}
